package m.jclecai.com.activity;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.ProofBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.Validator;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.BaseBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by ZD on 2017/7/10.
 */

public class SetUserNameActivity extends BaseActivity {
    @BindView(R.id.et_name)     //名字；
    EditText etName;
    @BindView(R.id.et_phone)    //电话；
    EditText etPhone;
    @BindView(R.id.et_password) //这个是密码；
    EditText etPassword;
    @BindView(R.id.text_bottom)
    TextView textBottom;
    Map<String, String> pair;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.tv_send_proof)
    TextView tvSendProof;

    @Override
    protected int getContentView() {
        return R.layout.activity_setname;
    }

    @Override
    protected void initData() {
        super.initData();
        leftOptionText("");
        setTitle("基本信息");
        pair = FastOk.get(getIntent().getStringExtra("param"), new TypeReference<Map<String, String>>() {
        });
        etName.setText(pair.get("nickname"));
        etName.setSelection(pair.get("nickname").length());
    }

    @OnClick(R.id.text_bottom)
    void submit() {
        if (TextUtils.isEmpty(etName.getText().toString())) {
            DisPlay("用户名不能为空");
            return;
        }
        if (!Validator.isMobile(etPhone.getText().toString())) {
            DisPlay("请填写正确的手机号");
            return;
        }
        if (TextUtils.isEmpty(etCode.getText().toString())) {
            DisPlay("请填写验证码");
            return;
        }
        if(TextUtils.isEmpty(etPassword.getText().toString())){
            DisPlay("请填写新密码");
            return;
        }
        isUserName();
       // startLogin();
    }

    private void startLogin() {

        Observable.empty().flatMap(new Func1<Object, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Object o) {
                return checkUserName();

            }
        }).flatMap(new Func1<Boolean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Boolean aBoolean) {
                return setNewName();
            }
        }).flatMap(new Func1<Boolean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Boolean aBoolean) {
                //重新设置密码；
                return null;
            }
        }).flatMap(new Func1<Boolean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Boolean aBoolean) {
                //检查验证码
                return checkPhoneRandomNumber();

            }
        }).flatMap(new Func1<Boolean, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(Boolean aBoolean) {
                //登陆
                return null;
            }
        }).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Boolean>() {
            @Override
            public void onStart() {
                showDialog();
            }
            @Override
            public void onCompleted() {
                dissDialog();
            }
            @Override
            public void onError(Throwable e) {
                //对异常进行一个判断；
                dissDialog();
                if(e instanceof RuntimeException){
                    RuntimeException exception = (RuntimeException) e;
                    DisPlay(exception.getMessage());
                }
            }

            @Override
            public void onNext(Boolean aBoolean) {
                //这里表示登陆成功；
            }
        });

    }



    @NonNull
    private Observable<Boolean> checkPhoneRandomNumber() {
        //是否输入了正确的手机验证码
        pair.put("vphone", etCode.getText().toString());//短信验证码
        pair.put("phone", etPhone.getText().toString());//绑定的手机号
        pair.put("flag", "4");//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        pair.put("appstore",ChannelUtil.getChannel() );//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        try {
            String responseStr = HttpManager.postAsString(Constant_Url.CHECK_PHONE_RANDNUM_URL, pair);
            if (!TextUtils.isEmpty(responseStr)) {
                ProofBean proofBean = FastOk.get(responseStr, ProofBean.class);
                if (proofBean != null && !proofBean.getStatus().equals("0")) {
                    return Observable.error(new RuntimeException(proofBean.getMessage()));
                }
            } else {
               return Observable.error(new RuntimeException("网络异常"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Observable.error(new RuntimeException("网络异常"));
        }
        return Observable.just(true);
    }

    @NonNull
    private Observable<Boolean> setNewName() {
        try {
            pair.put("name", etName.getText().toString());
            String responseStr = HttpManager.postAsString(Constant_Url.SETNAME, pair);

            ProofBean proofBean = FastOk.get(responseStr, ProofBean.class);
            if (proofBean != null) {
                if ("1".equals(proofBean.getStatus())) {
                    //存在此用户名，跳转
                    Observable.error(new RuntimeException("用户名已经存在"));
                }
            } else {
                Observable.error(new RuntimeException("网络请求出错"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            Observable.error(new RuntimeException("网络请求出错"));
        }

        return Observable.just(true);
    }

    //核实名字是否有人用过
    @NonNull
    private Observable<Boolean> checkUserName() {
        //验证用户名有否有人用过
        try {
            String responseStr = HttpManager.postAsString(Constant_Url.CHECK_USER_NAME_URL, pair);
            ProofBean proofBean = FastOk.get(responseStr, ProofBean.class);

            if (proofBean != null) {
                if ("1".equals(proofBean.getStatus())) {
                    //存在此用户名，跳转
                   // DisPlay(proofBean.getMessage());
                    return Observable.error(new RuntimeException("用户名已经存在"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Observable.error(new RuntimeException("网络请求出错"));
        }
        return Observable.just(true);
    }

    @Override
    protected void resetWindow() {

    }

    //未绑定手机号时发送验证码
    @OnClick(R.id.tv_send_proof)
    void sendProofWithOutBind() {
        String phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone) || !BaseUtils.isMobileNO(phone)) {
            MyToast.showToast(this, "请输入正确的手机号码");
            return;
        }
        showDialog();
        pair.put("phone", phone);
        HttpManager.postAsyn(Constant_Url.PROOF_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                MyToast.showToast(SetUserNameActivity.this, "验证码发送失败");
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null) {
                    MyToast.showToast(SetUserNameActivity.this, proofBean.getMessage());
                    if ("0".equals(proofBean.getStatus()))
                        BaseUtils.countDowm(SetUserNameActivity.this, 60, tvSendProof);
                } else {
                    MyToast.showToast(SetUserNameActivity.this, "验证码发送失败");
                }
            }
        }, pair);
    }

    /**
     * 判断是否存在此用户
     */
    private void isUserName() {
        showDialog();
 /*      */

        HashMap<String, String> pairm = new HashMap<>();
        pairm.put("user",etName.getText().toString());
        HttpManager.postAsyn(Constant_Url.CHECK_USER_NAME_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null) {
                    if ("1".equals(proofBean.getStatus())) {
                        //存在此用户名，跳转
                        DisPlay(proofBean.getMessage());
                    } else {
                        setUserName();
                    }
                } else {
                    dissDialog();
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pairm);
    }

    //设置用户名
    private void setUserName() {

        HashMap<String, String> pairm = new HashMap<>();
        pairm.put("name",etName.getText().toString());
        pairm.put("newValue",etPassword.getText().toString());
        pairm.put("user",pair.get("user"));
        pairm.put("password",pair.get("password"));

        HttpManager.postAsyn(Constant_Url.SETNAME, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                ProofBean proofBean = FastOk.get(response, ProofBean.class);
                if (proofBean != null) {
                    if ("1".equals(proofBean.getStatus())) {
                        //存在此用户名，跳转
                        DisPlay(proofBean.getMessage());
                        dissDialog();
                    } else {
                        bindPhone();
                    }
                } else {
                    dissDialog();
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pairm);
    }

    //绑定或更换手机号
    private void bindPhone() {
        //第一次绑定的时候vphone是验证码
        pair.put("vphone", etCode.getText().toString());//短信验证码
        pair.put("phone", etPhone.getText().toString());//绑定的手机号
        pair.put("flag", "4");//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        pair.put("appstore", ChannelUtil.getChannel());//标志flag=2 (修改密码)flag=3 (绑定手机)flag=4 (修改并绑定手机)
        HttpManager.postAsyn(Constant_Url.CHECK_PHONE_RANDNUM_URL, new HttpManager.StringCallback() {

            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                DisPlay(getString(R.string.error_network));
            }

            @Override
            public void onResponse(String response) {
                if (!TextUtils.isEmpty(response)) {
                    BaseBody baseBody = FastOk.get(response, BaseBody.class);
                    if (baseBody != null && baseBody.getStatus() == 0) {
                        //之类的时候，我们是需要做：
                        /*HashMap<String, String> map = new HashMap<>();
                        map.put("user",map.get("user"));
                        map.put("password",map.get("password"));
                        loadUserInfo(map);*/
                        logIn(etName.getText().toString(), etPassword.getText().toString(), new m.jclecai.com.listener.Callback() {
                            @Override
                            public void callbackSuccess() {
                                super.callbackSuccess();
                                setResult(Activity.RESULT_OK);
                                finish();
                            }

                            @Override
                            public void callbackField() {
                                super.callbackField();
                                DisPlay("登录失败请尝试手动登录！");
                            }
                        });
                    } else {
                        dissDialog();
                        DisPlay(getString(R.string.error_network));
                    }
                } else {
                    dissDialog();
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pair);
    }


    //登录后需要加载用户信息
    protected void loadUserInfo(final Map<String, String> pair) {
        showDialog();
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                UserBean userBean = FastOk.get(response, UserBean.class);
                if (userBean != null) {
                    if ("1011".equals(userBean.getStatus())) {
                        MyToast.showToast(SetUserNameActivity.this, "获取用户信息失败！");
                        PreferenceUtil.writeUser(SetUserNameActivity.this, null);
                    } else {
                        PreferenceUtil.setAccount(SetUserNameActivity.this, userBean.getPhone());
                        PreferenceUtil.setUserName(SetUserNameActivity.this, userBean.getUsername());
                        PreferenceUtil.setPassword(SetUserNameActivity.this, pair.get("password"));
                        PreferenceUtil.setLoginStatus(SetUserNameActivity.this, true);
                        PreferenceUtil.writeUser(SetUserNameActivity.this, userBean);
                        setResult(RESULT_OK);
                        SetUserNameActivity.this.finish();
                    }
                } else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pair);
    }
}
